package android.framework.binding;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;

public class BindableSpinner extends Spinner implements IBindable<String>, OnItemSelectedListener{

	private StringViewBindingHandler bindingHandler = new StringViewBindingHandler();
	private OnItemSelectedListener listener;
	
	public BindableSpinner(Context context, AttributeSet attrs) {
		super(context, attrs);
		super.setOnItemSelectedListener(this);
	}
	
	
	public BindableSpinner(Context context) {
		super(context);
	}
	
	public BindableSpinner(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public void setOnItemSelectedListener(OnItemSelectedListener listener){
		this.listener = listener;
	}
	
	public boolean notifyChanges(String value, long actionId) {
		boolean notifyChanges = bindingHandler.notifyChanges(value, actionId);
		if(notifyChanges){
			if(value == null){
				this.setSelection(-1);
			}
			if(getAdapter() != null){
				for (int position = 0; position < getAdapter().getCount(); position++) {
					String currentValue = getAdapter().getItem(position).toString();
					if(currentValue.equals(value)){
						this.setSelection(position);
					}
				}
			}
			
		}
		return notifyChanges;
	}

	public void addListener(IObserver<String> listener) {
		bindingHandler.addListener(listener);
	}

	public void removeListener(IObserver<String> listener) {
		bindingHandler.removeListener(listener);
	}

	public void setListener(MultiBindingAdapter<String> listener) {
		bindingHandler.setListener(listener);
	}

	public void clearListeners() {
		bindingHandler.clearListeners();
	}

	public String getLastValue() {
		return bindingHandler.getLastValue();
	}

	public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
			long arg3) {
		bindingHandler.onItemSelected(arg0, arg1, pos, arg3);
		if(listener != null){
			listener.onItemSelected(arg0, arg1, pos, arg3);
		}
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		bindingHandler.onNothingSelected(arg0);
		if(listener != null){
			listener.onNothingSelected(arg0);
		}
	}



}
